package com.agile.leetcode.easy.subaraymaxaverage;

/**
 * 求解子数组中k个数子数组的最大平均值
 *
 * @Author:ChenZhangKun
 * @Date: 2021/2/20 16:11
 */
public class FindSubArrayMaxAverage {
    public static void main(String[] args) {
        int[] nums = {1, 12, -5, -6, 50, 3};
        int k = 4;
        FindSubArrayMaxAverage average = new FindSubArrayMaxAverage();
        double maxAverage = average.findMaxAverage(nums, k);
        System.out.println(maxAverage);
    }

    /**
     * 拿到个数为k的子数组的最大平均数
     *
     * @param nums
     * @param k
     * @return
     */
    public double findMaxAverage(int[] nums, int k) {
        // 首先求出前K个数字的和
        int maxSum = 0;
        int sum = 0;
        for (int i = 0; i < k; i++) {
            sum += nums[i];
        }
        // 设置为最大值
        maxSum = sum;
        // 拿到数组的长度
        int n = nums.length;
        for (int i = k; i < n; i++) {
            // 滑动窗口，减去前面一个值加上最新的值
            sum = sum - nums[i - k] + nums[i];
            maxSum = Math.max(maxSum, sum);
        }
        return 1.0 * maxSum / k;
    }
}
